/**
 *  Copyright 2002-2009 the original author or authors.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package foo.bar.blog.core.domain;

import javax.persistence.*;
import java.util.Date;
import java.util.Set;
import java.util.LinkedHashSet;

/**
 * Representing a Blog domain object.
 *
 * @author tmjee
 * @version $Date: 2009-07-05 10:12:59 +0000 (Sun, 05 Jul 2009) $ $Id$
 */
@Entity
@EntityListeners({EntityAuditListener.class})
@Table(name="TBL_BLOG")
@NamedQueries({
    @NamedQuery(name="blog_findMemershipBlogIds",
        query="SELECT DISTINCT blog.id FROM Blog AS blog LEFT JOIN blog.members AS mem LEFT JOIN mem.id as memId WHERE memId = :memId"),
    @NamedQuery(name="blog_findOwnershipBlogIds",
        query="SELECT blog.id FROM Blog AS blog WHERE blog.owner = :owner"),
    @NamedQuery(name="blog_findOwnershipBlog",
        query="SELECT blog FROM Blog AS blog WHERE blog.owner = :owner"),
    @NamedQuery(name="blog_countOnwerhsipBlog",
        query="SELECT COUNT(blog) FROM Blog AS blog WHERE blog.owner = :owner"),
    @NamedQuery(name="blog_findMembershipBlog",
        query="SELECT DISTINCT blog FROM Blog AS blog LEFT JOIN blog.members AS mem  LEFT JOIN mem.id AS memId WHERE memId = :memId"),
    @NamedQuery(name="blog_countMembershipBlog",
        query="SELECT COUNT(DISTINCT blog) FROM Blog AS blog LEFT JOIN blog.members AS mem LEFT JOIN mem.id AS memId WHERE memId = :memId"),
    @NamedQuery(name="blog_findBlogById",
        query="SELECT blog FROM Blog AS blog WHERE blog.id = :id"),
    @NamedQuery(name="blog_findBlogEntries",
        query="SELECT entry FROM Entry AS entry WHERE entry.blog = :blog"),
    @NamedQuery(name="blog_countBlogEntries",
        query="SELECT count(entry) FROM Entry AS entry WHERE entry.blog = :blog"),
    @NamedQuery(name="blog_findBlogEntriesByState",
        query="SELECT entry FROM Entry as entry WHERE entry.blog = :blog AND entry.state = :state"),
    @NamedQuery(name="blog_countBlogEntriesByState",
        query="SELECT count(entry) FROM Entry as entry WHERE entry.blog = :blog AND entry.state = :state"),
    @NamedQuery(name="blog_findBlogEntriesByTagAndState",
        query="SELECT entry FROM Entry AS entry WHERE entry.blog = :blog AND entry.tag = :tag AND entry.state = :state"),
    @NamedQuery(name="blog_countBlogEntriesByTagAndState",
        query="SELECT count(entry) FROM Entry AS entry WHERE entry.blog = :blog AND entry.tag = :tag AND entry.state = :state"),
    @NamedQuery(name="blog_findLatestBlogs",
        query="SELECT blog FROM Blog as blog ORDER BY blog.creationDate DESC"),
    @NamedQuery(name="blog_findBlogByLikelyName",
        query="SELECT blog FROM Blog as blog WHERE LOWER(blog.name) like :blogName"),
    @NamedQuery(name="blog_countFindBlogByLikelyName",
        query="SELECT count(blog) FROM Blog as blog WHERE LOWER(blog.name) like :blogName"),
    @NamedQuery(name="blog_nonMembers",
        query="SELECT user FROM User as user WHERE user.id NOT IN (:memIds) AND user.id NOT IN (SELECT DISTINCT blog.owner.id FROM Blog as blog WHERE blog= :blog)"),
    @NamedQuery(name="blog_countNonMembers",
        query="SELECT count(user.id) FROM User as user WHERE user.id NOT IN (:memIds) AND user.id NOT IN (SELECT DISTINCT blog.owner.id FROM Blog as blog WHERE blog = :blog)"),
    @NamedQuery(name="blog_searchNonMembers",
        query="SELECT user FROM User as user WHERE user.id NOT IN (:memIds) AND user.id NOT IN (SELECT blog.owner.id FROM Blog as blog WHERE blog = :blog) AND (LOWER(user.username) LIKE :search)"),
    @NamedQuery(name="blog_countSearchNonMembers",
        query="SELECT count(user.id) FROM User as user WHERE user.id NOT IN (:memIds) AND user.id NOT IN (SELECT blog.owner.id FROM Blog as blog WHERE blog = :blog) AND (LOWER(user.username) LIKE :search)"),
    @NamedQuery(name="blog_members",
        query="SELECT mems FROM Blog as blog JOIN blog.members as mems WHERE blog = :blog"),
    @NamedQuery(name="blog_countMembers",
        query="SELECT count(mems) FROM Blog as blog JOIN blog.members as mems WHERE blog = :blog"),
    @NamedQuery(name="blog_datesOfBlogEntriesWithEntries",
        query="SELECT entry.publishDate FROM Entry AS entry WHERE entry.blog = :blog AND entry.publishDate IS NOT NULL AND entry.publishDate >= :startDate AND entry.publishDate <= :endDate"),
    @NamedQuery(name="blog_getBlogEntriesPublishedBetweenDates",
        query="SELECT entry FROM Entry as entry WHERE entry.blog = :blog AND entry.publishDate IS NOT NULL AND entry.publishDate >= :startDate AND entry.publishDate <= :endDate AND entry.state = foo.bar.blog.core.domain.EntryState.PUBLISHED"),
    @NamedQuery(name="blog_countBlogEntriesPublishedBetweenDates",
        query="SELECT count(entry) FROM Entry as entry WHERE entry.blog = :blog AND entry.publishDate IS NOT NULL AND entry.publishDate >= :startDate AND entry.publishDate <= :endDate AND entry.state = foo.bar.blog.core.domain.EntryState.PUBLISHED"),
    @NamedQuery(name="blog_searchBlogEntriesPublished",
        query="SELECT entry FROM Entry as entry WHERE entry.blog = :blog AND entry.state = foo.bar.blog.core.domain.EntryState.PUBLISHED AND(LOWER(entry.name) like :search OR LOWER(entry.description) like :search OR LOWER(entry.content) like :search)"),
    @NamedQuery(name="blog_countSearchBlogEntriesPublished",
        query="SELECT count(entry) FROM Entry as entry WHERE entry.blog = :blog AND entry.state = foo.bar.blog.core.domain.EntryState.PUBLISHED AND (LOWER(entry.name) like :search OR LOWER(entry.description) like :search OR LOWER(entry.content) like :search)"),
    @NamedQuery(name="blog_searchAllBlogEntriesPublished",
        query="SELECT entry FROM Entry as entry WHERE ((LOWER(entry.name) like :search OR LOWER(entry.description) like :search OR LOWER(entry.content) like :search) AND entry.state = foo.bar.blog.core.domain.EntryState.PUBLISHED)"),
    @NamedQuery(name="blog_countSearchAllBlogEntriesPublished",
        query="SELECT count(entry) FROM Entry as entry WHERE ((LOWER(entry.name) like :search OR LOWER(entry.description) like :search OR LOWER(entry.content) like :search) AND entry.state = foo.bar.blog.core.domain.EntryState.PUBLISHED)"),
    @NamedQuery(name="blog_countBlogByName",
        query="SELECT count(blog) FROM Blog AS blog where blog.name = :name"),
    @NamedQuery(name="blog_findAllBlogs",
        query="SELECT blog FROM Blog AS blog"),
    @NamedQuery(name="blog_countAllBlogs",
        query="SELECT count(blog) FROM Blog AS blog")
 })
public class Blog implements CreationInfoPersistable, ModificationInfoPersistable, Identifiable {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE, generator = "blogIdGenerator")
    @TableGenerator(name="blogIdGenerator", table = "TBL_ID_GENERATOR",
                    pkColumnName = "ID", valueColumnName = "ID_VALUE",
                    pkColumnValue = "TBL_BLOG_CURRENT_ID", initialValue = 1,
                    allocationSize = 10)
    @Column(name="ID", nullable = false)
    private long id;



    @OneToMany(targetEntity = Entry.class, cascade = {CascadeType.ALL}, mappedBy = "blog")
    @OrderBy("creationDate DESC, modificationDate DESC")
    private Set<Entry> entries;

    @ManyToOne(targetEntity = User.class)
    @JoinColumn(table = "TBL_BLOG", name="OWNER_ID", referencedColumnName = "ID")
    private User owner;

    @ManyToMany(targetEntity = User.class, cascade = {CascadeType.PERSIST})
    @JoinTable(name = "TBL_MEMBER_BLOG",
            joinColumns = {@JoinColumn(name="BLOG_ID", referencedColumnName = "ID")},
            inverseJoinColumns = {@JoinColumn(name="USER_ID", referencedColumnName = "ID")}
    )
    private Set<User> members = new LinkedHashSet<User>();


    @Basic
    @Column(name="NAME")
    private String name;

    @Basic
    @Column(name="DESCRIPTION")
    private String description;

    @Basic
    @Column(name="CREATION_DATE")
    private Date creationDate;

    @Basic
    @Column(name="MODIFICATION_DATE")
    private Date modificationDate;

    @ManyToOne(targetEntity = User.class)
    @JoinColumn(table = "TBL_BLOG", name = "CREATOR_ID", referencedColumnName = "ID")
    private User creator;

    @ManyToOne(targetEntity = User.class)
    @JoinColumn(table = "TBL_BLOG", name = "MODIFIER_ID", referencedColumnName = "ID")
    private User modifier;


    @Basic
    @Column(name="BLOG_THEME_NAME")
    private String blogThemeName;


    @OneToMany(targetEntity = Tag.class, cascade = {CascadeType.ALL}, mappedBy = "blog")
    private Set<Tag> tags = new LinkedHashSet<Tag>();


    @OneToMany(targetEntity = Link.class, cascade = {CascadeType.ALL}, mappedBy = "blog")
    private Set<Link> links = new LinkedHashSet<Link>();


    public void setTags(Set<Tag> tags) {
        this.tags = tags;
    }

    public Set<Tag> getTags() {
        return tags;
    }

    public void setLinks(Set<Link> links) {
        this.links = links;
    }

    public Set<Link> getLinks() {
        return links;
    }

    public String getBlogThemeName() {
        return blogThemeName;
    }

    public void setBlogThemeName(String blogThemeName) {
        this.blogThemeName = blogThemeName;
    }

    public Set<Entry> getEntries() {
        return entries;
    }

    public void setEntries(Set<Entry> entries) {
        this.entries = entries;
    }

    public User getOwner() {
        return owner;
    }

    public void setOwner(User owner) {
        this.owner = owner;
    }

    public Set<User> getMembers() {
        return members;
    }

    public void setMembers(Set<User> members) {
        this.members = members;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreator(User creator) {
        this.creator = creator;
    }

    public User getCreator() {
        return creator;
    }

    public void setModificationDate(Date modificationDate) {
        this.modificationDate = modificationDate;
    }

    public Date getModificationDate() {
        return modificationDate;
    }

    public void setModifier(User modifier) {
        this.modifier = modifier;
    }

    public User getModifier() {
        return modifier;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }


    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Blog blog = (Blog) o;

        if (name != null ? !name.equals(blog.name) : blog.name != null) return false;

        return true;
    }

    public int hashCode() {
        int result;
        result = (int) (id ^ (id >>> 32));
        result = 31 * result + (entries != null ? entries.hashCode() : 0);
        result = 31 * result + (owner != null ? owner.hashCode() : 0);
        result = 31 * result + (members != null ? members.hashCode() : 0);
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (description != null ? description.hashCode() : 0);
        result = 31 * result + (creationDate != null ? creationDate.hashCode() : 0);
        result = 31 * result + (modificationDate != null ? modificationDate.hashCode() : 0);
        result = 31 * result + (creator != null ? creator.hashCode() : 0);
        result = 31 * result + (modifier != null ? modifier.hashCode() : 0);
        return result;
    }

    public void addMember(User toBeAddedMember) {      
        if (!members.contains(toBeAddedMember)) {
             members.add(toBeAddedMember);
        }
        if (!toBeAddedMember.getMembershipBlogs().contains(this)) {
            toBeAddedMember.getMembershipBlogs().add(this);    
        }
    }

    public void removeMember(User member) {
        if (members.contains(member)) {
            members.remove(member);
        }
        if (member.getMembershipBlogs().contains(this)) {
            member.getMembershipBlogs().remove(this);
        }
    }
}
